// src/composables/useMembers.js
import { computed } from 'vue'
import { useTaskStore } from '@/stores/taskStore'

export function useMembers() {
  const store = useTaskStore()
  
  // 计算成员工作效率排名
  const getMemberEfficiencyRanking = () => {
    return computed(() => {
      return [...store.members]
        .map(member => {
          const completedTasks = store.tasks.filter(
            t => t.assignedTo === member.id && t.status === 'done'
          ).length
          const efficiency = member.capacity > 0 
            ? (completedTasks / member.capacity) * 100 
            : 0
          return {
            ...member,
            efficiency: Math.round(efficiency)
          }
        })
        .sort((a, b) => b.efficiency - a.efficiency)
    })
  }
  
  // 获取超负荷工作的成员
  const getOverloadedMembers = () => {
    return computed(() => {
      return store.members.filter(member => member.currentLoad > member.capacity)
    })
  }
  
  // 重新平衡任务分配
  const rebalanceTasks = () => {
    const unassignedTasks = store.tasks.filter(
      t => !t.assignedTo && t.status !== 'done'
    )
    
    unassignedTasks.forEach(task => {
      const availableMember = [...store.members]
        .sort((a, b) => (a.currentLoad / a.capacity) - (b.currentLoad / b.capacity))
        .find(m => m.currentLoad < m.capacity)
      
      if (availableMember) {
        task.assignedTo = availableMember.id
        availableMember.currentLoad += 1
      }
    })
  }
  
  return {
    getMemberEfficiencyRanking,
    getOverloadedMembers,
    rebalanceTasks
  }
}